package com.guonl.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

@Slf4j
public class SignatureUtil {

    public static String generateSign(String apiSecret, String methodName, String uri, String queryjsonStr, String timestamp) {
        String signatureString = String.format("%s\n%s\n%s\n%s", methodName, uri, DigestUtils.sha512Hex(queryjsonStr), timestamp);

        String signature = "";
        try {
            Mac hmacSha512 = Mac.getInstance("HmacSHA512");
            SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(), "HmacSHA512");
            hmacSha512.init(spec);
            signature = Hex.encodeHexString(hmacSha512.doFinal(signatureString.getBytes()));
        } catch (Exception e) {
            log.error("生成签名失败", e);
            throw new RuntimeException("生成签名失败");
        }
        return signature;
    }


}
